﻿CREATE PROCEDURE [dbo].[Planograms_InsertFromTempSpaces]
	@RangeReviewId int
AS

INSERT INTO Planograms (RangeReviewId, StoreId, Name, Modules, Width, Levels, PlanogramLocationId, Level1, Level2, TypeId, ListingPlanogramId)
	Select distinct @RangeReviewId, t.StoreId, t.Planogram, p.Modules, p.Width, p.Levels, p.PlanogramLocationId, p.Level1, p.Level2, p.TypeId, p.ListingPlanogramId 
	From TempSpaces t
	Left Outer Join Planograms p on t.Planogram = p.Name and t.StoreId = p.StoreId
	Where (p.Id is null OR (p.Id IS NOT NULL AND p.RangeReviewId != @RangeReviewId))
	order by Planogram
